//
//  HBTableViewCell.m
//  FMSManager
//
//  Created by hongbao.cui on 15-1-8.
//  Copyright (c) 2015年 hongbao.cui. All rights reserved.
//

#import "HBTableViewCell.h"
#import "ISMutileButton.h"
#import "ApplicationUtils.h"
@interface HBTableViewCell ()<UIWebViewDelegate>
@property(nonatomic, copy) NSURL *htmlURL;
@property(nonatomic, copy) NSString *html;
@property(nonatomic, copy) NSURL *baseURL;
@property(nonatomic, strong) UIWebView *webView;
@property(nonatomic, assign) BOOL ready;
@property(nonatomic, assign)CGFloat rowHeight;
@end

@implementation HBTableViewCell
-(CGSize )fontWithString:(NSString *)text size:(CGFloat)size Label:(UILabel *)titleLabel{
    UIFont *font = [UIFont systemFontOfSize:size];
    CGSize usersize = [text sizeWithFont:font constrainedToSize:CGSizeMake(270, 10000)lineBreakMode:NSLineBreakByWordWrapping];
    [titleLabel setLineBreakMode:NSLineBreakByCharWrapping];
    [titleLabel setNumberOfLines:0];
    [titleLabel setText:text];
    [titleLabel setFont:font];
    [titleLabel setBackgroundColor:[UIColor clearColor]];
    return usersize;
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier  DataDict:(NSDictionary *)dataDict
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        UIView *bgView = [[UIView alloc] initWithFrame:self.frame];
        UIImageView *mgView = [[UIImageView alloc] initWithFrame:CGRectMake(55, 0, self.frame.size.width-55, self.frame.size.height)];
        [mgView setImage:[UIImage imageNamed:@"selector_lib_item_bg.png"]];
        [mgView setTag:10];
        [bgView addSubview:mgView];
        self.selectedBackgroundView = bgView;
    }
    return self;
}
//-(void)drawRect:(CGRect)rect{
//    [super drawRect:rect];
//}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}
- (void)setHtmlFromURL:(NSURL  *)newHtmlURL {
    if (self.webView) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        [self.webView stopLoading];
    }
    else {
        [self prepare];
    }
    
    self.htmlURL = newHtmlURL;
    self.html = nil;
    self.baseURL = nil;
    self.ready = NO;
    
    self.webView.frame = [self frameForEmptyWebview];
    [self.webView loadRequest:[NSURLRequest requestWithURL:newHtmlURL]];
}

- (void)setHtml:(NSString  *)newHtml AndBaseURL:(NSURL *)newBaseURL {
    if (self.webView) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        [self.webView stopLoading];
    }
    else {
        [self prepare];
    }
    
    self.htmlURL = nil;
    //    NSString *cssName =@"screen.css";
    //    NSMutableString *htmlString =[[NSMutableString alloc]initWithString:@"<html>"];
    //    [htmlString appendString:@"<head>"];
    //    [htmlString appendString:@"<link rel =\"stylesheet\"href =\""];
    //    [htmlString appendString:cssName];
    //    [htmlString appendString:@"\"type=\"text/css\"/>"];
    //    [htmlString appendString:@"</head>"];
    //    [htmlString appendString:newHtml];
    //    [htmlString appendString:@"</html>"];
    self.html = newHtml;
    self.baseURL = newBaseURL;
    self.ready = NO;
    
    self.webView.frame = [self frameForEmptyWebview];
    [self.webView loadHTMLString:newHtml baseURL:newBaseURL];
}

- (CGFloat)height {
	return !self.ready ? 5 : [self.webView sizeThatFits:CGSizeZero].height;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    for (UIView *v in self.contentView.subviews) {
        v.alpha = (v==_webView);
    }
	CGRect f = self.contentView.bounds;
    f.origin.x = 50;
    f.size.width = self.frame.size.width-60;
	if (!self.ready) {
		f.size.height = 5;
    }else{
        f.size.height = [self.webView sizeThatFits:CGSizeZero].height;
    }
	self.webView.frame = f;
    
    UIImageView *bgView = (UIImageView *)[self.selectedBackgroundView viewWithTag:10];
    if (bgView) {
        [bgView setFrame:CGRectMake(55, 0, f.size.width, f.size.height)];
    }
}

- (void)didLoadData {
    self.ready = YES;
    float x,y,width,height;
    x=20;  y=5; width=30; height=30;
    _xinghao_btn=[[ISMutileButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [_xinghao_btn setBackgroundColor:[UIColor clearColor]];
    _xinghao_btn.isMultile = _isNeedB;
    //选择视图 30*30
    if (_isNeedB) {
        [_xinghao_btn setBackgroundImage:[ApplicationUtils getLocalImage:@"st_Options_mark_normal@2x"] forState:UIControlStateNormal];
        [_xinghao_btn setBackgroundImage:[ApplicationUtils getLocalImage:@"st_Options_mark_hover@2x"] forState:UIControlStateSelected];
    }else {
        [_xinghao_btn setBackgroundImage:[ApplicationUtils getLocalImage:@"st_Options_mark_d_normal"] forState:UIControlStateNormal];
        [_xinghao_btn setBackgroundImage:[ApplicationUtils getLocalImage:@"st_Options_mark_d_hover"] forState:UIControlStateSelected];
    }
    [_xinghao_btn setUserInteractionEnabled:NO];
    [self addSubview:_xinghao_btn];
    if (self.delegate) {
        [self.delegate tableCellDidLoadContent:self];
    }
}


#pragma mark - lifecycle

- (void)prepare {
    while(self.contentView.subviews.count) {
        [[self.contentView.subviews objectAtIndex:0] removeFromSuperview];
    }
    self.webView = [[UIWebView alloc] initWithFrame:[self frameForEmptyWebview]];
    self.webView.delegate = self;
    self.webView.userInteractionEnabled = NO;
    self.webView.autoresizingMask = 0;
    self.webView.backgroundColor = [UIColor clearColor];
    self.webView.opaque = NO;
    self.webView.scalesPageToFit = NO;
    [self.contentView addSubview:self.webView];
    
    //UIWebView和子视图同高
    //添加约束，使按钮在屏幕水平方向的中央
//    NSLayoutConstraint *centerXContraint=[NSLayoutConstraint
//                                          constraintWithItem:self.webView
//                                          attribute:NSLayoutAttributeHeight
//                                          relatedBy:NSLayoutRelationEqual
//                                          toItem:self
//                                          attribute:NSLayoutAttributeHeight
//                                          multiplier:1.0f
//                                          constant:0.0];
    //添加约束，使按钮在屏幕垂直方向的中央
//    NSLayoutConstraint *centerYContraint=[NSLayoutConstraint
//                                          constraintWithItem:self.webView
//                                          attribute:NSLayoutAttributeCenterY
//                                          relatedBy:NSLayoutRelationEqual
//                                          toItem:self
//                                          attribute:NSLayoutAttributeCenterY
//                                          multiplier:1.0f
//                                          constant:0.0];
    //给button的父节点添加约束
//    [self addConstraints:@[centerXContraint,centerYContraint]];
//    [self addConstraints:@[centerXContraint]];
}

- (void)dealloc {
    //    [NSObject cancelPreviousPerformRequestsWithTarget:self];
#if !__has_feature(objc_arc)
    [self.webView stopLoading];
    self.webView.delegate = nil;
    self.webView = nil;
    self.htmlURL = nil;
    self.html = nil;
    self.baseURL = nil;
    self.delegate = nil;
    [super dealloc];
#endif
    self.webView.delegate = nil;
}

#pragma mark - UIWebViewDelegate

- (void)webView:(UIWebView  *)aWebView didFailLoadWithError:(NSError  *)error {
    if ([error code] != 102 && [error code] != -999) {
        FMSCHBLog(@"webView failed to load %@. Error message: %@", aWebView.request.URL, error);
    }
}
- (void)webViewDidFinishLoad:(UIWebView  *)aWebView {
    [self didLoadData];
    [self setNeedsLayout];
}
- (BOOL)webView:(UIWebView  *)webView shouldStartLoadWithRequest:(NSURLRequest  *)request navigationType:(UIWebViewNavigationType)navigationType {
    if ([self.delegate respondsToSelector:@selector(tableCell:shouldStartLoadWithRequest:navigationType:)]) {
        return [self.delegate tableCell:self shouldStartLoadWithRequest:request navigationType:navigationType];
    }
    return YES;
}

#pragma mark - default empty frame

- (CGRect)frameForEmptyWebview {
    CGRect f = self.contentView.bounds;
    return [self.class frameForEmptyWebviewAssumingBounds:f];
}

+ (CGRect)frameForEmptyWebviewAssumingBounds:(CGRect)f {
    f.origin.y = 5;
    f.size.height = 5;
    return f;
}
@end
